<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="老人姓名" prop="elderUserId">
        <el-select
          v-model="queryParams.elderUserId"
          placeholder="请选择老人"
          clearable
        >
          <el-option
            v-for="item in elderOptions"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="费用类型" prop="feeType">
        <el-select
          v-model="queryParams.feeType"
          placeholder="请选择费用类型"
          clearable
        >
          <el-option
            v-for="dict in dict.type.sys_fee_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleRecharge"
          >充值</el-button
        >
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="feeList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="费用编号" align="center" prop="feeId" />
      <el-table-column
        label="老人账号"
        align="center"
        prop="elderUserName"
        width="120"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <el-tooltip :content="scope.row.elderUserName" placement="top">
            <span>{{ scope.row.elderUserName }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="费用类型" align="center" prop="feeType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_fee_type"
            :value="scope.row.feeType"
          />
        </template>
      </el-table-column>
      <el-table-column label="金额" align="center" prop="amount" />
      <el-table-column label="支付状态" align="center" prop="paymentStatus">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_payment_status"
            :value="scope.row.paymentStatus"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="支付时间"
        align="center"
        prop="paymentTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.paymentTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="账单编号" align="center" prop="billNo" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改费用管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="老人" prop="elderUserId">
          <el-select
            disabled
            v-model="form.elderUserId"
            placeholder="请选择老人"
          >
            <el-option
              v-for="item in elderOptions"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="费用类型" prop="feeType">
          <el-select
            disabled
            v-model="form.feeType"
            placeholder="请选择费用类型"
          >
            <el-option
              v-for="dict in dict.type.sys_fee_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input disabled v-model="form.amount" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item label="支付状态" prop="paymentStatus">
          <el-select
            disabled
            v-model="form.paymentStatus"
            placeholder="请选择支付状态"
          >
            <el-option
              v-for="dict in dict.type.sys_payment_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支付时间" prop="paymentTime">
          <el-date-picker
            disabled
            clearable
            v-model="form.paymentTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择支付时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="账单编号" prop="billNo">
          <el-input
            disabled
            v-model="form.billNo"
            placeholder="请输入账单编号"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 充值对话框 -->
    <el-dialog
      title="账户充值"
      :visible.sync="rechargeOpen"
      width="500px"
      append-to-body
    >
      <el-form
        ref="rechargeForm"
        :model="rechargeForm"
        :rules="rechargeRules"
        label-width="80px"
      >
        <el-form-item label="老人" prop="elderUserId">
          <el-select
            v-model="rechargeForm.elderUserId"
            placeholder="请选择老人"
          >
            <el-option
              v-for="item in elderOptions"
              :key="item.userId"
              :label="
                item.userName +
                ' (余额: ' +
                (item.balance || 0).toFixed(2) +
                '元)'
              "
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="充值金额" prop="amount">
          <el-input
            v-model="rechargeForm.amount"
            placeholder="请输入充值金额"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRecharge">确 定</el-button>
        <el-button @click="cancelRecharge">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFee, getFee, delFee, addFee, updateFee } from "@/api/system/fee";
import { listElder, recharge } from "@/api/system/user";

export default {
  name: "Fee",
  dicts: ["sys_fee_type", "sys_payment_status", "sys_payment_method"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 费用管理表格数据
      feeList: [],
      // 老人选项
      elderOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示充值弹出层
      rechargeOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        elderUserId: null,
        feeType: null,
        amount: null,
        paymentStatus: null,
        paymentTime: null,
        paymentMethod: null,
        billNo: null,
      },
      disabled: true,
      // 表单参数
      form: {},
      // 充值表单参数
      rechargeForm: {
        elderUserId: null,
        amount: null,
        paymentMethod: null,
      },
      // 表单校验
      rules: {
        elderUserId: [
          { required: true, message: "老人不能为空", trigger: "change" },
        ],
        feeType: [
          { required: true, message: "费用类型不能为空", trigger: "change" },
        ],
        amount: [{ required: true, message: "金额不能为空", trigger: "blur" }],
        paymentStatus: [
          { required: true, message: "支付状态不能为空", trigger: "change" },
        ],
        month: [{ required: true, message: "月份不能为空", trigger: "change" }],
      },
      // 充值表单校验
      rechargeRules: {
        elderUserId: [
          { required: true, message: "老人不能为空", trigger: "change" },
        ],
        amount: [
          { required: true, message: "充值金额不能为空", trigger: "blur" },
          {
            pattern: /^[1-9]\d*(\.\d{1,2})?$/,
            message: "请输入正确的金额",
            trigger: "blur",
          },
        ],
        paymentMethod: [
          { required: true, message: "支付方式不能为空", trigger: "change" },
        ],
      },
    };
  },
  mounted() {
    this.getList();
    this.getElderList();
  },
  activated() {
    this.getList();
    this.getElderList();
  },
  methods: {
    /** 查询费用管理列表 */
    getList() {
      this.loading = true;
      listFee(this.queryParams).then((response) => {
        this.feeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询老人列表 */
    getElderList() {
      listElder().then((response) => {
        this.elderOptions = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消充值按钮
    cancelRecharge() {
      this.rechargeOpen = false;
      this.rechargeForm = {
        elderUserId: null,
        amount: null,
        paymentMethod: null,
      };
    },
    // 表单重置
    reset() {
      this.form = {
        feeId: null,
        elderUserId: null,
        feeType: null,
        amount: null,
        paymentStatus: null,
        paymentTime: null,
        paymentMethod: null,
        billNo: null,
        description: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.feeId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 充值按钮操作 */
    handleRecharge() {
      this.rechargeOpen = true;
      this.getElderList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const feeId = row.feeId || this.ids;
      getFee(feeId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改费用管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.feeId != null) {
            updateFee(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFee(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 提交充值 */
    submitRecharge() {
      this.$refs["rechargeForm"].validate((valid) => {
        if (valid) {
          recharge(this.rechargeForm).then((response) => {
            this.$modal.msgSuccess("充值成功");
            this.rechargeOpen = false;
            this.getElderList(); // 刷新老人列表以更新余额
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const feeIds = row.feeId || this.ids;
      this.$modal
        .confirm('是否确认删除费用管理编号为"' + feeIds + '"的数据项？')
        .then(function () {
          return delFee(feeIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/fee/export",
        {
          ...this.queryParams,
        },
        `fee_${new Date().getTime()}.xlsx`
      );
    },
    getFeeTypeName(type) {
      const feeTypes = {
        1: "房费",
        2: "餐费",
        3: "护理费",
        4: "医疗费",
        99: "其他费用",
      };
      return feeTypes[type] || "未知类型";
    },
  },
};
</script>
